package com.sky.aspect;

import com.sky.annotation.AutoFill;
import com.sky.constant.AutoFillConstant;
import com.sky.context.BaseContext;
import com.sky.enumeration.OperationType;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;
import java.time.LocalDateTime;

@Slf4j
@Aspect
@Component
public class AutoFillAspect {

    @Pointcut("execution(* com.sky.mapper.*.*(..)) && @annotation(com.sky.annotation.AutoFill)")
    public void autoFillPointCut() {
    }

    @Before("autoFillPointCut()")
    public void autoFill(JoinPoint joinPoint) {
        log.debug("开始自动填充");
        try {
            // 1. 获取实体类对象
            Object[] args = joinPoint.getArgs();
            if (args == null || args.length == 0) {
                log.warn("拦截方法的参数为空");
                return;
            }
            Object entity = args[0];

            // 2. 获取注解的操作类型
            MethodSignature signature = (MethodSignature) joinPoint.getSignature();
            Method method = signature.getMethod();
            AutoFill annotation = method.getAnnotation(AutoFill.class);
            OperationType operationType = annotation.value();

            // 3. 根据不同操作类型填充数据
            Class<?> clazz = entity.getClass();
            LocalDateTime now = LocalDateTime.now();
            Long currentId = BaseContext.getCurrentId();
            // 3.1 插入类型/更新类型
            Method updateTimeMethod = clazz.getDeclaredMethod(AutoFillConstant.SET_UPDATE_TIME, LocalDateTime.class);
            updateTimeMethod.invoke(entity, now);
            Method updateUserMethod = clazz.getDeclaredMethod(AutoFillConstant.SET_UPDATE_USER, Long.class);
            updateUserMethod.invoke(entity, currentId);
            // 3.2 插入类型
            if (operationType == OperationType.INSERT) {
                Method createTimeMethod = clazz.getDeclaredMethod(AutoFillConstant.SET_CREATE_TIME, LocalDateTime.class);
                createTimeMethod.invoke(entity, now);
                Method createUserMethod = clazz.getDeclaredMethod(AutoFillConstant.SET_CREATE_USER, Long.class);
                createUserMethod.invoke(entity, currentId);
            }
        } catch (Exception e) {
            log.error("自动填充字段失败", e);
        }
    }

}
